#!/bin/bash
#
#***************************************************************
#Author:                            jiangkang
#Date:                              2024-09-02
#FileName:                          mysql_install.sh
#Description:                       The is MySQL install script
#***************************************************************

# 脚本启动错误处理
set -euo pipefail
trap 'echo "An unexpected error occurred. Exiting."; exit 1;' ERR

# 日志文件路径
LOGFILE="/var/log/mysql_install.log"

# 记录日志函数
log()
{
  echo "$(date '+%Y-%m-%d %H:%M:%S') $*" | tee -a $LOGFILE
}

log "Starting MySQL 5.7 installation script..."

# 1.检查是否以root用户或使用sudo运行
if [ "$EUID" -ne 0 ]; then
  log "Please run as root or with sudo."
  exit 1
fi

# 2.检查并处理SELinux
log "Checking SELinux status..."
if getenforce | grep -qw "Enforcing"; then 
  log "SELinux is Enforcing.Setting it to Permissive temporarily..."
  setenforce 0
  SELINUX_SET=1
else 
  SELINUX_SET=0
fi

# 3.检查是否安装了MySQL
if rpm -qa | grep -qw mysql; then 
  log "MySQL is already installed. Stopping and uninstalling it."

  # 停止MySQL服务
  if systemctl is-active --quiet mysqld;then 
    log "Stopping MySQL service..."
    systemctl stop mysqld || { log "Failed to stop MySQL service. Exiting."; exit 1; }
  fi

  # 备份现有的MySQL数据库和配置文件
  BACKUP_DIR="/root/mysql_backup_$(date '+%Y%m%d%H%M%S')"
  mkdir -p $BACKUP_DIR
  log "Backing up MySQL data and configuration to $BACKUP_DIR..."
  cp -r /var/lib/mysql /etc/my.cnf $BACKUP_DIR/ || { log "Backup failed. Exiting."; exit 1; }

  # 卸载MySQL
  log "Removing MySQL packages..."
  #yum remove -y mysql mysql-server mysql-libs mysql-devel mysql-community-server || { log "Failed to remove MySQL packages. Exiting."; exit 1; }
  yum remove -y `rpm -qa | grep mysql` || { log "Failed to remove MySQL packages. Exiting."; exit 1; }

  # 清理残留的MySQL数据和配置文件
  log "Cleaning up MySQL data and configuration files..."
  rm -rf /var/lib/mysql /etc/my.cnf /etc/mysql /var/log/mysqld.log || { log "Failed to clean MySQL files. Exiting."; exit 1; }
else 
  log "No existing MySQL installation found. Proceeding with the installation."
fi

# 4.检查并替换失效的CentOS YUM源
log "Checking YUM repository status..."
if ! yum repolist &> /dev/null; then 
  log "YUM repository is not accessible. Attempting to replace with a functional mirror."

  # 备份原有的YUM仓库配置
  cp /etc/yum.repos.d/CentOS-Base.repo{,.bak}

  # 替换为可用的腾旭云镜像源
  log "Replacing YUM repository with Tencent Cloud mirror..."
  cat >/etc/yum.repos.d/CentOS-Base.repo <<EOF
[base]
name=CentOS-\$releasever - Base - mirrors.tencent.com
baseurl=https://mirrors.tencent.com/centos-vault/7.9.2009/os/\$basearch/
gpgcheck=1
gpgkey=https://mirrors.tencent.com/centos-vault/RPM-GPG-KEY-CentOS-7

[updates]
name=CentOS-\$releasever - Updates - mirrors.tencent.com
baseurl=https://mirrors.tencent.com/centos-vault/7.9.2009/updates/\$basearch/
gpgcheck=1
gpgkey=https://mirrors.tencent.com/centos-vault/RPM-GPG-KEY-CentOS-7

[extras]
name=CentOS-\$releasever - Extras - mirrors.tencent.com
baseurl=https://mirrors.tencent.com/centos-vault/7.9.2009/extras/\$basearch/
gpgcheck=1
gpgkey=https://mirrors.tencent.com/centos-vault/RPM-GPG-KEY-CentOS-7
EOF
  
  # 清理和更新YUM缓存
  yum clean all
  yum makecache || { log "Failed to update YUM cache with the new repository. Exiting."; exit 1; }
fi

# 5.更新系统包
log "Updating system package..."
yum upgrade -y || { log "Failed to update system packages. Exiting."; exit 1; }

# 6.安装必备工具
log "Installing necessary tools..."
yum install -y wget yum-utils || { log "Failed to install necessary tools. Exiting."; exit 1; }

# 7.添加MySQL5.7的YUM存储库
log "Adding MySQL 5.7 YUM repository"
if ! rpm -qa | grep -qw mysql57-community-release; then
  wget https://dev.mysql.com/get/mysql57-community-release-el7-11.noarch.rpm || { log "Failed to download MySQL 5.7 YUM repository. Exiting."; exit 1; }
  rpm -ivh mysql57-community-release-el7-11.noarch.rpm || { log "Failed to install MySQL 5.7 YUM repository. Exiting."; exit 1; }
else 
  log "MySQL 5.7 YUM repository is already installed."
fi

# 8.确保启用了MySQL 5.7的存储库
log "Configuring MySQL YUM repository..."
yum-config-manager --disable mysql80-community || { log "Failed to disable MySQL 8.0 repository. Exiting."; exit 1; }
yum-config-manager --enable mysql57-community || { log "Failed to enable MySQL 5.7 repository. Exiting."; exit 1; }


# 9.安装MySQL5.7
log "Installing MySQL 5.7..."
yum install -y mysql-community-server --nogpgcheck || { log "Failed to install MySQL 5.7. Exiting."; exit 1; }

# 12.配置跳过密码登录
log "Set up a skip password login"
sed -i '/^\s*\[mysqld\]/a skip-grant-tables' /etc/my.cnf

# 10.启动MySQL服务并配置开机自启动
log "Starting MySQL service..."
systemctl start mysqld || { log "Failed to start MySQL service. Exiting."; exit 1; }
systemctl enable mysqld || { log "Failed to enable MySQL service at startup. Exiting."; exit 1; }

# 11.检查MySQL数据目录权限
DATA_DIR="var/lib/mysql"
log "Checking MySQL data directory permissions..."
if ! sudo -u mysql test -r "$DATA_DIR" && sudo -u mysql test -w "$DATA_DIR"; then
  log "Correcting MySQL data directory permissions..."
  chown -R mysql:mysql "$DATA_DIR" || { log "Failed to set permissions on MySQL data directory. Exiting."; exit 1; }
fi

# 14.检查MySQL服务状态
log "Checking MySQL service status..."
systemctl status mysqld || { log "MySQL service is not running correctly. Please check the logs."; exit 1; }

# 15.恢复SELinux状态
if [ $SELINUX_SET -eq 1 ]; then 
  log "Restoring SELinux to Enforcing mode..."
  setenforce 1;
fi

# 16.提示完成
log "MySQL 5.7 installation and initial configuration are complete."
